import sqlite3
import os

# 切换到项目目录
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# 数据库文件路径
db_path = 'database.db'

print("数据库修复脚本")
print(f"工作目录: {os.getcwd()}")
print(f"数据库路径: {db_path}")

# 检查数据库文件
if not os.path.exists(db_path):
    print("创建新的数据库文件...")
    with open(db_path, 'w') as f:
        pass

# 连接数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 检查sessions表
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
table_exists = cursor.fetchone()

if not table_exists:
    print("创建sessions表...")
    cursor.execute("""
        CREATE TABLE sessions (
            id VARCHAR(36) PRIMARY KEY,
            name VARCHAR(100) NOT NULL DEFAULT '默认会话',
            user_id VARCHAR(36),
            status VARCHAR(20) NOT NULL DEFAULT 'active',
            category VARCHAR(20) NOT NULL DEFAULT 'default',
            interaction_count INTEGER NOT NULL DEFAULT 0,
            research_count INTEGER NOT NULL DEFAULT 0,
            session_metadata TEXT,
            created_at TIMESTAMP NOT NULL,
            updated_at TIMESTAMP NOT NULL,
            closed_at TIMESTAMP,
            search_vector VARCHAR(1000)
        )
    """)
    print("sessions表创建成功")
else:
    # 检查category列
    cursor.execute("PRAGMA table_info(sessions)")
    columns = cursor.fetchall()
    column_names = [col[1] for col in columns]
    
    if 'category' not in column_names:
        print("添加category列...")
        cursor.execute("ALTER TABLE sessions ADD COLUMN category VARCHAR(20) DEFAULT 'default'")
        print("category列添加成功")
    else:
        print("category列已存在，无需修复")

conn.commit()
conn.close()
print("数据库修复完成！")